package com.ysu.his.admin.service.impl;

import cn.hutool.json.JSONUtil;
import com.ysu.his.admin.mapper.RoleMapper;
import com.ysu.his.admin.service.RoleService;
import com.ysu.his.constant.RedisConstant;
import com.ysu.his.entity.user.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl implements RoleService
{
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Override
    public List<Role> getAllRoles()
    {
        List<Object> roleJsonStrList = redisTemplate.opsForHash().values(RedisConstant.ALL_ROLE);

        List<Role> roleList = roleJsonStrList.stream()
                .map(role -> JSONUtil.toBean((String)role,Role.class))
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(roleList))
        {
            roleList = roleMapper.getAllRole();
        }
        return roleList;
    }
}
